<template>
  <div class="policy_list_page">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      label-width="97px"
    >
      <el-form-item label="线下活动名称" prop="activityName">
        <el-input
          v-model="queryParams.activityName"
          placeholder="请输入线下活动名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型" prop="activityType">
        <el-select
          v-model="queryParams.activityType"
          placeholder="请选择类型"
          class="select_box"
        >
          <el-option
            :label="item.label"
            :value="item.value"
            v-for="(item, index) in customerGroupList"
            :key="index"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="机构" prop="strategyOrgan">
        <el-cascader
            style="width: 240px"
            clearable
            @change="strategyOrganChange"
            :options="organizationList"
            :props="organizationList_props"
            v-model="strategyOrgan"
            :show-all-levels="false"
            placeholder="请选择组织机构"
          >
          </el-cascader>
      </el-form-item>
      <el-form-item label="渠道" prop="channelCode">
        <el-select v-model="queryParams.channelCode" placeholder="请选择渠道">
          <el-option
            :label="item.label"
            :value="item.value"
            v-for="(item, index) in channelList"
            :key="index"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >查询</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="openDetail('add')"
          >新建</el-button
        >
      </el-col>
    </el-row>
    <!-- @selection-change="handleSelectionChange" -->
    <el-table v-loading="loading" :data="policyListShow">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="活动Id" align="center" width="120" prop="activityId" />
      <el-table-column label="线下活动名称" align="center" prop="activityName" />
      <el-table-column label="类型" align="center" prop="activityTypeName" />
      <el-table-column label="渠道" align="center" prop="channelName" />
      <el-table-column label="机构" align="center" prop="organName" />
      <el-table-column label="活动地点" align="center" prop="activityAddress" width="300"/>
      <!-- <el-table-column label="创建人" align="center" prop="creator" /> -->
      <!-- <el-table-column label="状态" sortable align="center" prop="activityStatus" width="100"
      :filters="[{ text: '已完成', value: '1' }, { text: '未开始', value: '2' },{ text: '进行中', value: '3' }]"
      :filter-method="filterTag"
      filter-placement="bottom-end">
        <template slot-scope="scope">
          <div style="display: flex;align-items: center;" v-if="scope.row.status == '1'">
            <div style="width: 8px;height: 8px;border-radius: 8px;background-color: rgb(17,169,131);"></div>
            <span style="margin-left: 8px;">已完成</span>
          </div>
          <div style="display: flex;align-items: center;" v-if="scope.row.status == '3'">
            <div style="width: 8px;height: 8px;border-radius: 8px;background-color: rgb(17,169,131)"></div>
            <span style="margin-left: 8px;">进行中</span>
          </div>
          <div style="display: flex;align-items: center;" v-if="scope.row.status == '2'">
            <div style="width: 8px;height: 8px;border-radius: 8px;background-color: #909399"></div>
            <span style="margin-left: 8px;">未开始</span>
          </div>
          
        </template>
      </el-table-column> -->
      <el-table-column
        label="创建时间"
        align="center"
        prop="insertTimeStr"
        width="180"
        sortable
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="120"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="openDetail('preview', scope.row)"
            >预览</el-button
          > -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="openDetail('edit',scope.row)"
            >编辑</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="pageNum"
      :limit.sync="pageSize"
      @pagination="getList"
    />
    <el-dialog :title="title" :visible.sync="open" width="380px" append-to-body>
      <el-form
        :model="addForm"
        :rules="rules"
        ref="addForm"
        size="small"
        :inline="true"
        label-width="80px"
      >
        <el-form-item label="活动名称" prop="activityName">
          <el-input
            style="width: 240px"
            v-model="addForm.activityName"
            placeholder="请输入线下活动名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="类型" prop="activityType">
          <el-select
            style="width: 240px"
            v-model="addForm.activityType"
            placeholder="请选择类型"
            class="select_box"
          >
            <el-option
              :label="item.label"
              :value="item.value"
              v-for="(item, index) in customerGroupList"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="机构" prop="strategyOrgan">
          <span slot="label">
            <span style="color: #FF574C;margin-right: 4px;">*</span>
            <span>机构</span>
          </span>
          <el-cascader
            style="width: 240px"
            clearable
            @change="strategyOrganChange2"
            :options="organizationList"
            :props="organizationList_props"
            v-model="strategyOrgan2"
            :show-all-levels="false"
            placeholder="请选择组织机构"
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="渠道" prop="channelCode">
          <el-select v-model="addForm.channelCode" placeholder="请选择渠道" style="width: 240px">
            <el-option
              :label="item.label"
              :value="item.value"
              v-for="(item, index) in channelList"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="活动地点" prop="activityAddress">
          <el-input
            style="width: 240px"
            type="textarea"
            :rows="3"
            v-model="addForm.activityAddress"
            placeholder="请输入线下活动地点"
            clearable
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitclick">确 定</el-button>
        <el-button @click="cancelclick">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
// import { listPost, getPost, delPost, addPost, updatePost } from "@/api/policyConfiguration/index";
import axios from "axios";
export default {
  name: "offlineActivityM",
  data() {
    return {
      customerGroupList: [],
      channelList: [],
      organizationList: [],
      organizationList_props: {
        multiple: false,
        label: "organName",
        value: "organCode",
        children: "childOrganList",
        checkStrictly: true,
      },
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      // 是否显示弹出层
      open: false,
      // 表格数据
      policyListShow: [{
        activityId:'1'
      }],
      dataList: [],
      // 查询参数
      strategyOrgan2:[],
      strategyOrgan:[],
      queryParams: {
        // organId: ''
      },
      pageNum: 1,
      pageSize: 10,
      // 表单参数
      addForm: {
        activityId:'',
        organId:'',
        activityName:'',
        activityType: '',
        channelCode: '',
        activityAddress:''
      },
      // 表单校验
      rules: {
        activityName: [
          { required: true, message: "活动名称不能为空", trigger: "blur" },
        ],
        activityType: [
          { required: true, message: "类型不能为空", trigger: "blur" },
        ],
        // organizationValue: [
        //   { required: true, message: "机构不能为空", trigger: "blur" },
        // ],
        channelCode: [
          { required: true, message: "渠道不能为空", trigger: "blur" },
        ],
        activityAddress: [
          { required: true, message: "活动地点不能为空", trigger: "blur" },
        ],
      },
      ids: null,
      title: "新建活动",
      multiple:[]
    };
  },
  mounted () {
  },
  created () {
    this.getList()
    this.getEnumList()
  },
  methods: {
    strategyOrganChange (val) {
      if (val.length !== 0) {
        this.queryParams.organId = val[val.length - 1];
      } else { 
        this.queryParams.organId = ''
      }
    },
    strategyOrganChange2 (val) {
      console.log(val);
      if (val.length !== 0) {
        this.getParentId(this.organizationList,val[val.length - 1])
        this.addForm.organId = val[val.length - 1];
      } else { 
        this.addForm.organId = ''
      }
    },
    async getEnumList() {
      try {
        const response = await axios.post(
          process.env.VUE_APP_BASE_API + "/strategy/queryEnumList",
          {}
        );
        if (response.data.enumList) {
          if (response.data.enumList.activityType) {
            this.customerGroupList = response.data.enumList.activityType;
          }
          if (response.data.enumList.channelType) {
            this.channelList = response.data.enumList.channelType;
          }
          if (response.data.enumList.organList) {
            this.organizationList = JSON.parse(
              response.data.enumList.organList
            )
          }
        }
      } catch (error) {
        console.error("Error fetching users:", error);
      }
    },
    // 多选框选中数据
    // handleSelectionChange(selection) {
    //   this.ids = selection.map(item => item.id)
    //   this.multiple = selection
    // },
    getecharts () { 
    },
    filterTag(value, row) {
      return row.status === value
    },
    // 去除对象中为null、''的属性
    resultQueryParams (obj) {
      return Object.entries(obj).reduce((a, [k, v]) => ((v == null || v == '') ? a : ((a[k] = v), a)), {})
    },
    getParentId(list, id) {
      for (let i in list) {
        if (list[i].organCode === id) {
          this.addForm.organName = list[i].organName
          return [list[i].organCode];
        }
        if (list[i].childOrganList != null) {
          let node = this.getParentId(list[i].childOrganList, id);
          if (node !== undefined) {
            return node.concat(list[i].organCode);
          }
        }
      }
    },
    async getList () {
      this.loading = true;
      try {
        const resultBject = this.resultQueryParams(this.queryParams)
        const response = await axios.post(process.env.VUE_APP_BASE_API +
          '/activity/queryActivityList?pageNum=' + this.pageNum + '&pageSize=' + this.pageSize, {
          ...resultBject,
          activityGroup:'down'
          });
        this.policyListShow = response.data.rows;
        this.dataList =response.data.rows;
        this.total = response.data.total;
        this.loading = false;
      } catch (error) {
        this.loading = false;
        console.error('Error fetching users:', error);
      }
    },
    resetQuery() {
      this.queryParams = this.$options.data().queryParams
      this.strategyOrgan = []
      this.policyListShow = this.dataList;
      this.resetForm("form");
    },
    handleQuery() {
      this.pageNum = 1;
      this.getList()
    },
    async submitclick () { 
      if (this.strategyOrgan2.length==0) { 
        return this.$message.warning('机构不可为空')
      }
      this.$refs.addForm.validate((valid) => {
        if (valid) {
            axios.post(
              process.env.VUE_APP_BASE_API + "/activity/insertOrUpdateActivity",
              {
                ...this.addForm,
                activityGroup: 'down'
              }
            ).then(response => { 
              if (response.data.code == 200) {
                this.open = false
                this.handleQuery()
                this.$message.success('新增成功')
              }
            }).catch(error => { 
              console.error("Error fetching users:", error);
            })
        }
      })
    },
    cancelclick () { 
      this.open = false
    },
    openDetail (type, data) {
      if (type == 'add') {
        this.title = '新建活动'
        this.strategyOrgan2 = []
        this.addForm = this.$options.data().addForm
        this.open = true
      } else if (type == 'edit') {
        this.title = '编辑活动'
        this.strategyOrgan2 = []
        this.addForm = this.$options.data().addForm
        // 通过id查询：
        // data.activityId
        axios.post(
          process.env.VUE_APP_BASE_API + "/activity/queryActivityById",
          { activityId:data.activityId }
        ).then(response => {
          if (response.data) {
            this.addForm.activityId = response.data.activityId
            this.addForm.organId = response.data.organId
            this.strategyOrgan2 = this.getParentId(this.organizationList,this.addForm.organId).reverse()
            this.addForm.activityName = response.data.activityName
            this.addForm.activityType = response.data.activityType
            this.addForm.channelCode = response.data.channelCode
            this.addForm.activityAddress = response.data.activityAddress
            this.open = true
          }
        }).catch(error => {
          console.error("Error fetching users:", error);
        })
      }
    },
    // 任务状态修改
    // handleStatusChange(row) {
    //   let text = row.status === "0" ? "启用" : "停用";
    //   this.$modal
    //     .confirm('确认要"' + text + '""' + row.activityName + '"策略吗？')
    //     .then(() => {
    //       row.status = row.status === "0" ? "1" : "0";
    //       let currentIndex = this.dataList.findIndex((item) => {
    //         return item.id == row.id;
    //       });

    //       if (currentIndex == 0 || (currentIndex && currentIndex != -1)) {
    //         this.dataList.splice(currentIndex, 1, row);
    //       }
    //       this.policyListShow = this.dataList;
    //       this.$modal.msgSuccess(text + "成功");
    //     })
    //     .catch(function () {
    //       row.status = row.status === "0" ? "1" : "0";
    //     });
    // },
  },
};
</script>
<style lang="scss" scoped>
.policy_list_page {
  padding: 32px;
  .head_title {
    font-size: 32px;
    font-weight: 600;
  }
  .search_head {
    width: 100%;
    background: #fff;
    height: 100px;
    margin-bottom: 32px;
    padding-left: 40px;
    .search_form {
      width: 100%;
      display: inline-flex;
    }
  }
}
</style>
